import datetime
from other.cfg import Config
from other.change_format import change_format
from other.sql_montage import sqlMontage
from other.status import Status
from server.Mysql import MySQL


class attributes:
    def __init__(self):
        self.cfg = Config()
        self.st = Status()
        self.db = MySQL(self.cfg.res['mysql']['database'], 'attributes')
        self.cf = change_format()
        self.sm = sqlMontage()

    # 获取属性列表
    def get_attribute_list(self, data):
        result = {'msg': '成功', 'code': 200, 'data': [], 'total': None}
        sqls = "where 1=1 "
        sql = ""
        if data != {}:
            if data.get('attributeName') is not None:
                if data['attributeName'] != '':
                    sql = sql + " and `attribute_name` like '%{}%'".format(data['attributeName'])
 
        total = self.db.get(sqls + sql)
        result['total'] = len(total)
        if sql != "":
            sql = sqls + sql 
        else:
            sql = sqls
        res = self.db.get(sql)
        if res != ():
            for r in res:
                for key, value in r.items():
                    if isinstance(value, datetime.datetime):
                        r[key] = value.strftime("%Y-%m-%d %H:%M:%S")
                # 关联查询 attribute_options 表
                options_sql = f"SELECT * FROM attribute_options WHERE `attribute_id` = {r.get('attribute_id')}"
                options_res = self.db.gets(options_sql)
                value_str = []
                for a in options_res:
                    value_str.append(a.get('option_key'))
                r['values'] = options_res
                r['value_str'] = '; '.join(value_str)
                result['data'].append(r)
        result = self.cf.changes_format(result)
        return result


    # 新增
    def add_attribute(self, data,userInfo):
        result = {'msg': '成功', 'code': 200}
        g_sql = f"where `attribute_name`='{data['attributeName']}'"
        g_res = self.db.get(g_sql)
        if g_res != ():
            result['code'] = 500
            result['msg']= '属性名称重复'
        else:
            add_sql = self.sm.add_sql_data(data, 'attributes')
            attribute_id =  self.db.adds(add_sql, 'attributes')
            
        for v in data['values']:
            v['attributeId'] = attribute_id
            add_sql = self.sm.add_sql_data(v, 'attribute_options')
            self.db.adds(add_sql, 'attribute_options')
        return result
    

    # 修改
    def edit_attribute(self, data, userInfo):
        result = {'msg': '成功', 'code': 200}
        g_sql = f"where `attribute_name`='{data['attributeName']}'"
        g_res = self.db.get(g_sql)
        ff = False
        if g_res != ():
            for g in g_res:
                if g['attribute_id'] == data['attributeId']:
                    ff = True
                else:
                    if g['attribute_name'] == data['attributeName']:
                        result['msg'] = '属性名称重复'
                    ff = False
                    result['code'] = 500
                    break
        else:
            ff = True
        if ff:
            edit_sql = self.sm.edit_sql_data(data, 'attributes', 'attribute_id', data['attributeId'])
            self.db.edits(edit_sql, 'attributes')
            
            # 获取属性表里所有的选项
            s_sql = f"select `option_id` from `attribute_options` where `attribute_id`='{data['attributeId']}'"
            s_res = self.db.gets(s_sql)
     
            # 传入的选项
            params_options = []
            for v in data['values']:
                if 'optionId' in v and v['optionId'] is not None and  v['optionId'] != '':
                    edit_sql_v = self.sm.edit_sql_data(v, 'attribute_options', 'option_id',v['optionId'])
                    self.db.edits(edit_sql_v, 'attribute_options')
                    params_options.append(v['optionId'])
                else:
                    v['attributeId'] = data['attributeId']
                    add_sql = self.sm.add_sql_data(v, 'attribute_options')
                    self.db.adds(add_sql, 'attribute_options')
            
            #没有传入的选项，走删除操作
            for s in s_res:
                try:
                    index = params_options.index(s['option_id'])
                except ValueError:
                    dtd_sql = f"delete from `attribute_options` where `option_id`='{s['option_id']}'"
                    self.db.edits(dtd_sql, 'attribute_options')
        return result


    # 删除
    def del_attribute(self, data, userInfo):
        result = {'msg': '成功', 'code': 200}
        ids = [int(x) for x in data.split(',')]
        for i in ids:
            # 删除
            dr_sql = f"where `attribute_id`={i}"
            g_res = self.db.get(dr_sql)
            
            if g_res != ():
                for g in g_res:
                    dtd_sql = f"delete from `attribute_options` where `attribute_id`='{i}'"
                    self.db.edits(dtd_sql, 'attribute_options')
            self.db.delete(dr_sql)
       
        return result
